package api

import (
	"github.com/EDDYCJY/go-gin-app/pkg/e"
	"github.com/EDDYCJY/go-gin-app/pkg/logging"
	"github.com/EDDYCJY/go-gin-app/pkg/response"
	"github.com/EDDYCJY/go-gin-app/pkg/upload"
	"github.com/gin-gonic/gin"
)

func UploadImage(c *gin.Context) {
	code := e.SUCCESS
	data := make(map[string]string)
	msg := ""
	file,image,err := c.Request.FormFile("image")
	if err != nil {
		logging.Warn(err)
		code = e.ERROR
	} else {
		if image == nil {
			code = e.INVALID_PARAMS
		} else {
			imageName := upload.GetImageName(image.Filename)
			fullPath := upload.GetImageFullPath()
			savePath := upload.GetImagePath()

			src := fullPath + imageName
			if !upload.CheckImageExt(imageName) || !upload.CheckImageSize(file) {
				code = e.ERROR_UPLOAD_CHECK_IMAGE_FORMAT
			} else {
				err = upload.CheckImage(fullPath)
				if err != nil {
					logging.Warn(err)
					code = e.ERROR_UPLOAD_CHECK_IMAGE_FAIL
				} else if err = c.SaveUploadedFile(image, src); err != nil {
					logging.Warn(err)
					code = e.ERROR_UPLOAD_SAVE_IMAGE_FAIL
				} else {
					data["image_url"] = upload.GetImageFullUrl(imageName)
					data["image_save_url"] = savePath + imageName
				}
			}
		}
	}

	response.ApiReturn(c, code, data, msg)
}
